//
//  MNDMyProfileViewController.m
//  minidai
//
//  Created by 容贤郁 on 2017/5/7.
//  Copyright © 2017年 迷你金服. All rights reserved.
//

#import "MNDMyProfileViewController.h"
#import <SDWebImage/UIButton+WebCache.h>
#import "NSString+ReplaceAsterisk.h"
#import "MNDChangePhoneSendCaptchaViewController.h"
#import "MNDSettingViewController.h"
#import "MNDDepositAlertViewController.h"
#import "MNDModifyUserNameViewController.h"
#import "APIManager.h"
#import "MNDRiskAssessWebViewController.h"

#import "RSAUtil.h"
#import "MNDOpenDepositoryViewController.h"
#import "MNDDepositBankCardViewController.h"
#import <AFNetWorking.h>
#import "MNDManagerAccountViewController.h"
#import <ShareSDKExtension/SSEThirdPartyLoginHelper.h>
#import "MNDBindWechatTableViewController.h"
#import <ShareSDKExtension/ShareSDK+Extension.h>

/*! 记录小红点是否已显示过 */
#define kNewFeatureDot   @"newFeatureDot"

@interface MNDMyProfileViewController () <UITableViewDataSource, UITableViewDelegate,UINavigationControllerDelegate,UIImagePickerControllerDelegate>

@property (weak, nonatomic) IBOutlet UIButton *userAvatarBtn;
@property (weak, nonatomic) IBOutlet UILabel *usernameLabel;

@property (weak, nonatomic) IBOutlet UIImageView *avatarArrow;
@property (weak, nonatomic) IBOutlet UIImageView *userRealnameArrow;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *avatarSpace;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *realnameSpace;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *userNameSpace;
@property (weak, nonatomic) IBOutlet UIImageView *userNameArrow;
@property (weak, nonatomic) IBOutlet UILabel *userPhoneLabel;

@property (weak, nonatomic) IBOutlet UILabel *wechatBindLabel;

/**
 存管状态
 */
@property (weak, nonatomic) IBOutlet UILabel *depositLabel;

/**
 风险评测状态
 */
@property (weak, nonatomic) IBOutlet UILabel *riskAssessmentStatusLabel;

/**
 是否开户
 */
@property (nonatomic, assign) BOOL isOpenAccount;

/**
 小红点
 */
@property (weak, nonatomic) IBOutlet UIView *redDotView;

@end

@implementation MNDMyProfileViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
//    [self initialBarbuttonItems];
    
    [self configUserInfo:self.user];
    
    if ([UserDefaultsTool boolForKey:kNewFeatureDot]) {
        [self.redDotView setHidden:YES];
    }
}

- (void)initialBarbuttonItems {
    //创建UIBarButtonSystemItemFixedSpace
    UIBarButtonItem * spaceItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace
                                                                                target:nil action:nil];
    //将宽度设为负值
    spaceItem.width = kScreenWidth < 414? -10 : -15;
    UIBarButtonItem *item = [[UIBarButtonItem alloc] initWithTitle:@"账号管理"
                                                             style:UIBarButtonItemStylePlain
                                                            target:self
                                                            action:@selector(goSettingAction:)];
    [item setTitleTextAttributes:@{NSFontAttributeName: [UIFont fontWithName:@"PingFangSC-Regular" size:14.0]} forState:UIControlStateNormal];
    [item setTintColor:kColorBlack];
    
    if (@available(iOS 11.0, *)) {
        self.navigationItem.rightBarButtonItem = item;
    } else {
        self.navigationItem.rightBarButtonItems = @[spaceItem, item];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:animated];

    NSArray *leftBarButtonItems = self.navigationItem.leftBarButtonItems;
    for (UIBarButtonItem *item in leftBarButtonItems) {
        [item setTintColor:kColorBackButtonColor];
    }
    
    [self loadUserInfos];
    
}

#pragma mark - Network

- (void)loadUserInfos {
    
    WeakSelf(self);
    [NetworkProgressHUD showHud];
    [APIManager sendRequestWithPath:API_USER_BASE_INFO
                         parameters:[MNDSign signedParam]
                             method:kXMHTTPMethodGET
                          onSuccess:^(ResponseModel *responseModel) {
                              
                              if (responseModel.status == ResponseSuccess) {
                                  [NetworkProgressHUD hideHud];
                                  weakself.user = [MNDUserModel mj_objectWithKeyValues:responseModel.data];
                                  NSLog(@"data: %@", responseModel.data);
                                  [weakself configUserInfo:weakself.user];
                              } else {
                                  NSDictionary *dict = responseModel.msg;
                                  if (dict && dict.count > 0) {
                                      [NetworkProgressHUD showHudMsg:dict[@"error"]];
                                  } else {
                                      [NetworkProgressHUD showHudMsg:@"获取数据失败"];
                                  }
                              }
                          } onFailure:^(NSError *error) {
                              [NetworkProgressHUD showHudNetworkError:error];
                          }];
}

- (void)configUserInfo:(MNDUserModel *)userModel {
    UIImage *avatarPlaceholder = [UIImage imageNamed:@"user_center_avatar_color"];
    if (userModel.userPhoto.length > 0) {
        [self.userAvatarBtn sd_setImageWithURL:[NSURL URLWithString:userModel.userPhoto]
                                      forState:UIControlStateNormal
                              placeholderImage:avatarPlaceholder];
    } else {
        [self.userAvatarBtn setImage:avatarPlaceholder forState:UIControlStateNormal];
    }

    self.avatarSpace.constant = 15.0;
    
    self.usernameLabel.text = userModel.userName;
    
    if (userModel.userModifyNum.integerValue == -1) {
        [self.userNameArrow setHidden:YES];
        self.userNameSpace.constant = 15.0;
    }
    
    if (userModel.userRiskEvaluationState.integerValue == -1) {
        self.riskAssessmentStatusLabel.text = @"立即测评";
        self.riskAssessmentStatusLabel.textColor = kColorDarkOrange;
    } else {
        self.riskAssessmentStatusLabel.text = userModel.userRiskEvaluationType;
        self.riskAssessmentStatusLabel.textColor = kColor9;
    }
    self.userPhoneLabel.text = [userModel.userPhone replaceWithAsteriskAtRange:NSMakeRange(3, 4)];
    
    if (userModel.is_bind_weixin == 1) {//已绑定
        self.wechatBindLabel.text = @"已绑定";
        self.wechatBindLabel.textColor = kColor9;
    }else {//未绑定
        self.wechatBindLabel.text = @"立即绑定";
        self.wechatBindLabel.textColor = kColorDarkOrange;
    }
    
}


#pragma mark - Action
//修改头像
- (IBAction)changeIconImageAction:(UIButton *)sender {
    //弹窗
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIPopoverPresentationController *popVC = alert.popoverPresentationController;
    popVC.sourceView = sender;
    popVC.sourceRect = sender.bounds;
    popVC.permittedArrowDirections = UIPopoverArrowDirectionUp;
    //相机
    [alert addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self photoFromCamera];
        
    }]];
    //相册
    [alert addAction:[UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self photoFromAlbum];
    }]];
    //取消
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
    [self presentViewController:alert animated:YES completion:nil];
}

//账号管理
- (void)goSettingAction:(id)sender {
    MNDManagerAccountViewController *accountVC = [UIStoryboard viewControllerWithIdentifier:@"MNDManagerAccountViewController"];
    accountVC.user = self.user;
    [self.navigationController pushViewController:accountVC animated:YES];
//    [self performSegueWithIdentifier:[MNDSettingViewController description] sender:nil];
}

//登出
- (IBAction)logoutAction:(id)sender {

}

//相机获取头像
- (void)photoFromCamera {
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;//设置类型为相机
        UIImagePickerController *picker = [[UIImagePickerController alloc] init];//初始化
        picker.delegate = self;//设置代理
        picker.allowsEditing = YES;//设置照片可编辑
        picker.sourceType = sourceType;
        //设置是否显示相机控制按钮 默认为YES
        picker.showsCameraControls = YES;
    
        //选择前置摄像头或后置摄像头
        picker.cameraDevice=UIImagePickerControllerCameraDeviceFront;
        [self presentViewController:picker animated:YES completion:^{
        }];
    } else {
        NSLog(@"该设备无相机");  
    }
}

//相册获取头像
- (void)photoFromAlbum {
    //首先需要判断资源是否可用
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        
        UIImagePickerController *pickerImage = [[UIImagePickerController alloc] init];
        
        pickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        //获得相机模式下支持的媒体类型
        //        pickerImage.mediaTypes = [UIImagePickerController availableMediaTypesForSourceType:pickerImage.sourceType];
        pickerImage.delegate = self;
        //设置允许编辑
        pickerImage.allowsEditing = YES;
        
        [self presentViewController:pickerImage animated:YES completion:^{
        }];
    }
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    //获取裁剪后的图像
    UIImage *image = info[UIImagePickerControllerEditedImage];
    //将照片存到媒体库
//    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
    //将照片存到沙盒
    [self saveImage:image];
    
//    [self.userAvatarBtn.imageView setImage:image];
    [self.userAvatarBtn setImage:image forState:UIControlStateNormal];
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark - 取消操作时调用
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
    [picker dismissViewControllerAnimated:YES completion:^{
    }];
}

#pragma mark - 保存图片
- (void) saveImage:(UIImage *)currentImage {
    //设置照片的品质
    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.5);
    
    NSLog(@"%@",NSHomeDirectory());
    // 获取沙盒目录
    NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/currentImage.jpg"];
    // 将图片写入文件
    [imageData writeToFile:filePath atomically:NO];
    
    MNDLoginUserModel *user = [MNDLoginUserModel currentLoginUser];
    
    NSString *userID = [self rsaEncode: user.user_id];
    
    //表单上传
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];//初始化请求对象
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];//设置服务器
    [manager POST:API_ICON_IMAGE parameters:@{@"user_id":userID} constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        [formData appendPartWithFileData:imageData name:@"file_upload_ats" fileName:filePath mimeType:@"image/jpg"];
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        NSLog(@"uploadProgress = %@",uploadProgress);
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        ResponseModel *response = [ResponseModel mj_objectWithKeyValues:responseObject];
        if (response.status == ResponseSuccess) {
            [self loadUserInfos];
        }else {
            NSLog(@"上传失败");
        }
        NSLog(@"------------ %@---------", responseObject);
        NSLog(@"responseobj: %@", responseObject);
        NSLog(@"responseObject = %@, task = %@",responseObject,task);
        NSDictionary *obj = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
        NSLog(@"obj = %@",obj[@"error_msg"]);

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         NSLog(@"error = %@",error);
    }];
   //    将选择的图片显示出来
//        [self.photoImage setImage:[UIImage imageWithContentsOfFile:filePath]];
    
}

- (void)image:(UIImage*)image didFinishSavingWithError:(NSError*)error contextInfo:(void*)contextInfo{
    if (!error) {
        NSLog(@"存储成功");
    } else {
        NSLog(@"存储失败：%@", error);
    }
}

- (NSString *)rsaEncode:(NSString *)rsaStr {
    NSString *encryText = [RSAUtil encryptString:[NSString stringWithFormat:@"%@", rsaStr] publicKey:RSA_PUBLIC_KEY];
    NSString *unreserved = @"";
    NSMutableCharacterSet *allowed = [NSMutableCharacterSet alphanumericCharacterSet];
    [allowed addCharactersInString:unreserved];
    
    NSString *encodeEncryText = [encryText stringByAddingPercentEncodingWithAllowedCharacters:allowed];
    
    return encodeEncryText;
    
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        //判断是否安装微信，未安装则隐藏微信登录
        if (![ShareSDK isClientInstalled:SSDKPlatformTypeWechat]) {
            return 3;
        }else {
            return 4;
        }
    }else {
        return 1;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    [self.redDotView setHidden:YES];
    [UserDefaultsTool saveBool:YES forKey:kNewFeatureDot];
    
    if (indexPath.section == 0) {
        if (indexPath.row == 1 && self.user.userModifyNum.integerValue == 1) {//用户名
            UIStoryboard *storyboard = [UIStoryboard storyboardWithName:[MNDModifyUserNameViewController description] bundle:nil];
            
            MNDModifyUserNameViewController *modifyVC = [storyboard instantiateViewControllerWithIdentifier:[MNDModifyUserNameViewController description]];
            
            [self.navigationController pushViewController:modifyVC animated:YES];
        }
        
        if (indexPath.row == 2) {//注册手机号更改
            [self performSegueWithIdentifier:[MNDChangePhoneSendCaptchaViewController description] sender:nil];
        }
        
        if (indexPath.row == 3) {//微信bang'd
            if (![self.wechatBindLabel.text isEqualToString:@"立即绑定"]) {
                return;
            }
            [SSEThirdPartyLoginHelper loginByPlatform:SSDKPlatformTypeWechat
                                           onUserSync:^(SSDKUser *user, SSEUserAssociateHandler associateHandler) {
                                               NSLog(@"user = %@",user);
                                               //在此回调中可以将社交平台用户信息与自身用户系统进行绑定，最后使用一个唯一用户标识来关联此用户信息。
                                               //在此示例中没有跟用户系统关联，则使用一个社交用户对应一个系统用户的方式。将社交用户的uid作为关联ID传入associateHandler。
                                               [NetworkProgressHUD showHud];
                                               if (user.uid.length <= 0) {
                                                   user.uid = @"";
                                               }
                                               if (user.nickname.length <= 0) {
                                                   user.nickname = @"";
                                               }
                                               if (user.icon.length <= 0) {
                                                   user.icon = @"";
                                               }
                                               
                                               
                                               NSDictionary *params = @{
                                                                        @"unionid":user.credential.rawData[@"unionid"],
                                                                        @"open_id": user.credential.rawData[@"openid"],
                                                                        @"open_name": user.nickname,
                                                                        @"open_img": user.icon,
                                                                        @"open_sex": user.gender == 0 ? @(-1):@(1),
                                                                        @"open_type": @"1",
                                                                        @"source": @"app"
                                                                        };
                                               kdeclare_weakself;
                                               //开始登录
                                               [APIManager sendRequestWithURL:API_WECHAT_LOGIN parameters:[MNDSign signedParamWithDict:params] method:kXMHTTPMethodPOST onSuccess:^(ResponseModel *responseModel) {
                                                   [NetworkProgressHUD hideHud];
                                                   if (responseModel.status == ResponseSuccess) {
                                                       NSString *str = responseModel.data[@"is_bind"];
                                                       
                                                       if (str.integerValue == -1) {//未绑定
                                                           [weakSelf goBindWechat:(SSDKUser *)user];
                                                       }else {//已绑定
                                                           [NetworkProgressHUD showHudMsg:@"该微信号已绑定其他账户"];
                                                       }
                                                       
                                                       NSLog(@"responseModel = %@",responseModel);
                                                   }else {
                                                       [NetworkProgressHUD showHudMsg:responseModel.msg[@"error"]];
                                                   }
                                               } onFailure:^(NSError *error) {
                                                   [NetworkProgressHUD showHudNetworkError:error];
                                               }];
                                               associateHandler (user.uid, user, user);
                                               NSLog(@"dd%@",user.rawData);
                                               NSLog(@"dd%@",user.credential);
                                               
                                           }
                                        onLoginResult:^(SSDKResponseState state, SSEBaseUser *user, NSError *error) {
                                            
                                            if (state == SSDKResponseStateSuccess)
                                            {
                                                
                                            }
                                            
                                        }];
            
        }
    }
    
    if (indexPath.section == 1) {
//        //存管
//        if (indexPath.row == 0) {
//            if (!self.isOpenAccount) {
//                [self toOpenDepository];
//            } else {
//                MNDDepositBankCardViewController *bankCardVC = [UIStoryboard viewControllerWithIdentifier:[MNDDepositBankCardViewController description]];
//                [self.navigationController pushViewController:bankCardVC animated:YES];
//            }
//        }
//        //风险测评
        if (indexPath.row == 0) {
            
            NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
            MNDRiskAssessWebViewController *riskVC = [[MNDRiskAssessWebViewController alloc]init];
            riskVC.webViewUrl = self.user.evaluationUrl;
            riskVC.title = @"风险测评";
            riskVC.indexOfViewController = index;
            [self.navigationController pushViewController:riskVC animated:YES];
        }
    }
}

//绑定微信
- (void)goBindWechat:(SSDKUser *)user {
    MNDBindWechatTableViewController *bindVC = [UIStoryboard viewControllerWithIdentifier:@"MNDBindWechatTableViewController"];
    bindVC.isUserCenterEnter = YES;
    bindVC.userPhone = self.user.userPhone;
    bindVC.user = user;
    [self.navigationController pushViewController:bindVC animated:YES];
}

//- (void)toOpenDepository {
//
//    NSInteger index = [self.navigationController.viewControllers indexOfObject:self];
//    MNDOpenDepositoryViewController *realVC = [UIStoryboard viewControllerWithIdentifier:[MNDOpenDepositoryViewController description]];
//    realVC.fromNaviIndex = index;
//
//    [self.navigationController pushViewController:realVC animated:YES];
//}

#pragma mark - Navigation

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    if ([segue.identifier isEqualToString:[MNDChangePhoneSendCaptchaViewController description]]) {
        MNDChangePhoneSendCaptchaViewController *changeVC = segue.destinationViewController;
        
        changeVC.userModel = self.user;
    }
}


@end
